/**
 * Created by jiadx on 2015/11/13.
 */
define(['ionic'], function() {
    angular.module('SalesShipments.services', [])
        .factory('SalesShipmentsService', ['$http', '$q', function($http, $q) {
            var o = {},
                dataCache = {
                    division: [],
                    contactCache: [],
                    merchandiseCache: [],
                    searchContact: []
                },
                shoppingCart = {},
                selectContacts = {},
                selectDivision = {},
                loadContact = [],
                localBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAOQAAADjCAIAAAAaMC9iAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAA9nSURBVHhe7Z3pdqPMDgDv+7/oTOIldpx4GTuZWyfqj+MB3EAbY0mofuTECUsDhVq9gP/39+/fX0FggZA1MEPIGpghZA3MELIGZghZAzOErIEZQtbADCFrYIaQNTBDyBqYIWQNzBCyBmYIWQMzhKyBGULWwAwha2CGkDUwQ8gamCFkDcwQsgZmCFkDM4SsgRlC1sAMIWtghpA1MEPIGpghZA3MELIGZghZAzOErIEZQtbADCFrYIaQNTBDyBqYwbmsm83mdDp9fX19f3/z83w+Hw6H9/f35XKZlgjs4FnW3W7H0d0Cd/f7fVhrCLeyvr6+ipSdEHrX63VaTQG/f//mFtputx8fH8fj8c+fP5cf+IW7a7FYpOXmh1tZPz8/xcWeoMJqtUorPwPuLvIT7hwyllSmNvjvbGsDt7ISiuTqDoLQRWBLm5gKbhIiaCpBD7iv0pozw6es/XOAJqjw8vKSNvQvVMFvb2+kwrTSpHYm8ZW1pAEnlTX/pQanbddZZRMjWV62MIjnVgLPwqesKCUXtQwEquKr1M5EvnztfAvWYl22wHZkgxX8MS00HGqAtJU54VPWezwQSHnZyPl8Tp/HgK2xTQnbd5aQKC5HOit8yjq0dTUlxFryhPThDmbYLeBT1lFsUA6pTjra2RCyWoV2Xjra2eBTVtofckUdQ6qTjnY2RM5qlRl2CPiU9ePjQ66oYzjGdLSzwaes2+1WrqhjNptNOtrZ4FPW1WolV9QxzVEG9/iU9eXlRa6oVy6X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ULWwAwha2CGkDUwQ8gamCFkDcwQsgZmCFkDM4SsgRlC1sAMIWtghpA1MEPIGpghZA3MELIGZghZAzOErIEZQtbADCFrYIaQNTBDyBqYIWQNzBCyBmYIWQMzhKyBGULWwAwha2CGkDUwQ8gamCFkDcwQsgZG+PXr/1VFs+tIYhKoAAAAAElFTkSuQmCC';

            function lowercase(string) {
                return isString(string) ? string.toLowerCase() : string;
            }

            function isString(value) {
                return typeof value === 'string';
            }

            //事业部
            o.queryDivision = function() {
                var defer = $q.defer();
                var orgId = u9.getLoginData().OrgId;
                if (dataCache.division.length > 0) {
                    u9.hideLoading();
                    defer.resolve(angular.copy(dataCache.division));
                } else {
                    u9.callSV({
                        name: 'UFIDA.U9.ISV.MFGSDShipSV.Ship.IGetDocTypeByOrg',
                        params: [orgId],
                        onSuccess: function(data) {
                            dataCache.division = data;
                            u9.hideLoading();
                            defer.resolve(data);
                        },
                        onFailure: function(err) {
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    });
                }
                return defer.promise;
            };
            o.selectDivision = function(addData) {
                var defer = $q.defer();
                if (addData) {
                    selectDivision = addData;
                    u9.hideLoading();
                    defer.resolve(addData);
                } else {
                    u9.hideLoading();
                    defer.reject();
                }
                return defer.promise;
            };

            //客户
            o.queryContacts = function(pageId, keywords) {
                var defer = $q.defer();
                u9.showLoading();
                var orgId = u9.getLoginData().OrgId;
                if (pageId == 1) {
                    dataCache.contactCache = [];
                }
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGSDShipSV.Ship.IGetCustomerListByOrg',
                    params: [orgId, pageId, keywords],
                    onSuccess: function(data) {
                        if (data.length > 0) {
                            angular.forEach(data, function(user) {
                                var camelChars = pinyin.getCamelChars(user.Name);
                                var enName = pinyin.getFullChars(user.Name).toLowerCase();
                                user.EnName = enName;
                                if (user.Gather == '') {
                                    user.Gather = 100;
                                }
                            });
                            if (keywords != '') {
                                dataCache.searchContact = dataCache.searchContact.concat(data);
                                var contactFlag = true;
                                if (dataCache.searchContact.length < 10) {
                                    contactFlag = false;
                                }
                                defer.resolve({
                                    contact: dataCache.searchContact,
                                    flag: contactFlag
                                });
                            } else {
                                dataCache.searchContact = [];
                                dataCache.contactCache = dataCache.contactCache.concat(data);
                                defer.resolve({
                                    contact: dataCache.contactCache,
                                    flag: true
                                });
                            }

                        } else {
                            if (keywords != '') {
                                dataCache.searchContact = dataCache.searchContact.concat(data);
                                defer.resolve({
                                    contact: dataCache.searchContact,
                                    flag: false
                                });
                            } else {
                                defer.resolve({
                                    contact: dataCache.contactCache,
                                    flag: false
                                });
                            }
                        }
                        u9.hideLoading();
                    },
                    onFailure: function(err) {
                        u9.hideLoading();
                        defer.reject(err);
                    }
                });

                return defer.promise;
            };
            o.selectContacts = function(addData) {
                var defer = $q.defer();
                if (addData) {
                    selectContacts = addData;
                    u9.hideLoading();
                    defer.resolve(addData);
                } else {
                    u9.hideLoading();
                    defer.reject();
                }
                return defer.promise;
            };
            o.getContactByValue = function(value) {
                var defer = $q.defer();
                u9.showLoading();
                var arr = [];
                angular.forEach(dataCache.contactCache, function(info) {
                    if (info.EnName.indexOf(lowercase('' + value)) != -1) {
                        arr.push(info);
                    }
                });
                u9.hideLoading();
                defer.resolve(arr);
                return defer.promise;
            };

            //商品
            o.queryMerchandise = function(pages, customerId, isRefresh) {
                var defer = $q.defer();
                u9.showLoading();
                if (pages == 1 || isRefresh) {
                    dataCache.merchandiseCache = [];
                }
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGSDShipSV.Ship.IGetItemMasterList',
                    params: [pages, customerId],
                    onSuccess: function(data) {
                        if (dataCache.merchandiseCache.length > 0 && data.length > 0 && data[data.length - 1].MerchandiseId == dataCache.merchandiseCache[dataCache.merchandiseCache.length - 1].MerchandiseId) {
                            defer.resolve({
                                merchandise: dataCache.merchandiseCache,
                                flag: false
                            });
                        } else {
                            angular.forEach(data, function(mer) {
                                var enName = pinyin.getFullChars(mer.Name).toLowerCase();
                                mer.enName = enName;
                                if (shoppingCart.hasOwnProperty(mer.MerchandiseId)) {
                                    mer.add = true;
                                } else {
                                    mer.add = false;
                                }
                                if (mer.Picture == '') {
                                    mer.Picture = 'data:image/JPG;base64,' + localBase64;
                                } else {
                                    mer.Picture = 'data:image/JPG;base64,' + mer.Picture;
                                }
                            });
                            dataCache.merchandiseCache = dataCache.merchandiseCache.concat(data);
                            defer.resolve({
                                merchandise: dataCache.merchandiseCache,
                                flag: true
                            });
                        }
                        u9.hideLoading();
                    },
                    onFailure: function(err) {
                        u9.hideLoading();
                        defer.reject(err.message);
                    }
                });
                return defer.promise;
            };
            o.addMerchandise = function(checked, addData) {
                var defer = $q.defer();
                if (checked == true) {
                    if (addData) {
                        //dataCache.shoppingCart = dataCache.shoppingCart.concat(addData);
                        shoppingCart[addData.merchandiseId] = addData;
                        defer.resolve(checked);
                        u9.hideLoading();
                    } else {
                        u9.hideLoading();
                        defer.reject();
                    }
                } else {
                    if (addData) {
                        //dataCache.shoppingCart = dataCache.shoppingCart.concat(addData);
                        delete shoppingCart[addData.merchandiseId];
                        defer.resolve(checked);
                        u9.hideLoading();
                    } else {
                        u9.hideLoading();
                        defer.reject();
                    }
                }

                return defer.promise;
            };
            o.getMerchandiseByValue = function(value, customerId) {
                var defer = $q.defer();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGSDShipSV.Ship.IQueryInfoByKeyword',
                    params: [value, customerId],
                    onSuccess: function(data) {
                        angular.forEach(data, function(mer) {
                            var enName = pinyin.getFullChars(mer.Name).toLowerCase();
                            mer.enName = enName;
                            if (mer.Picture == '') {
                                mer.Picture = 'data:image/JPG;base64,' + localBase64;
                            } else {
                                mer.Picture = 'data:image/JPG;base64,' + mer.Picture;
                            }
                        });
                        u9.hideLoading();
                        defer.resolve(data);
                    },
                    onFailure: function(err) {
                        u9.hideLoading();
                        defer.reject(err.message);
                    }
                });
                return defer.promise;
            };

            //下单
            o.getDivision = function() {
                return selectDivision;
            };
            o.getContact = function() {
                return selectContacts;
            };
            o.getMerchandise = function() {
                return shoppingCart;
            };
            o.clearShoppingCart = function() {
                shoppingCart = {};
            };
            o.deleteShoppingCart = function(deleteData) {
                delete shoppingCart[deleteData.merchandiseId];
            };
            o.buyOrders = function(orderList) {
                var defer = $q.defer();
                u9.showLoading();
                u9.callSVAlone({
                    name: 'UFIDA.U9.ISV.MFGSDShipSV.Ship.ICreateShip',
                    params: [orderList],
                    onSuccess: function(flag) {
                        u9.hideLoading();
                        defer.resolve(flag);
                    },
                    onFailure: function(err) {
                        u9.hideLoading();
                        defer.reject(err);
                    }
                });
                return defer.promise;
            };
            return o;
        }]);
});